package com.syh.jn.scm.service.impl.supplier.sale;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syh.core.ddd.event.annotation.DomainEventHandle;
import com.syh.core.ddd.infrastructure.repository.AggregateRepository;
import com.syh.core.ddd.service.AbstractServiceImpl;
import com.syh.jn.scm.domain.operation.entity.supplier.OperaSupplier;
import com.syh.jn.scm.domain.operation.event.supplier.OperaSupplierEvent;
import com.syh.jn.scm.domain.supplier.entity.sale.SaleOrder;
import com.syh.jn.scm.domain.supplier.event.SaleOrderEvent;
import com.syh.jn.scm.domain.support.entity.History;
import com.syh.jn.scm.domain.support.repository.HistoryRepository;
import com.syh.jn.scm.dto.supplier.sale.SaleOrderVo;
import com.syh.jn.scm.dto.support.HistoryDto;
import com.syh.jn.scm.dto.support.HistoryVo;
import com.syh.jn.scm.service.api.supplier.sale.SaleOrderService;
import com.syh.jn.scm.service.api.supplier.sale.SaleOrderHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * Created by soci.song on 2019/1/18.
 */
@Service
@Transactional
public class SaleOrderHistoryServiceImpl extends AbstractServiceImpl<HistoryDto, HistoryDto, HistoryVo, History, Long> implements SaleOrderHistoryService {

  @Resource(name = "saleHistoryRepositoryImpl")
  private HistoryRepository saleHistoryRepository;
  @Autowired
  private SaleOrderService saleOrderService;

  @Override
  protected AggregateRepository<History, Long> getAggregateRepository() {
    return this.saleHistoryRepository;
  }

  @Override
  public Long save(HistoryDto dto) {
    SaleOrderVo sale = saleOrderService.getById(dto.getOriginalId());
    dto.buildHistory(JSONObject.parseObject(JSON.toJSONString(sale)));
    return saleHistoryRepository.add(new History(dto));
  }

  /**
   * 消费者：监听销售单删除（删除该单的历史记录）
   *
   * @param saleOrder
   */
  @DomainEventHandle(SaleOrderEvent.SALEORDER_DESTORY)
  protected void handleSaleOrderDestory(SaleOrder saleOrder) {
    this.saleHistoryRepository.deleteHistorysByOriginalId(saleOrder.getId());
  }

  /**
   * 消费者：监听服务商反开账（删除所有该服务商的销售单历史记录）
   */
  @DomainEventHandle(OperaSupplierEvent.SUPPLIER_REVERSAL_ACCOUNT)
  protected void handleSupplierReversalAccount(OperaSupplier supplier) {
    this.saleHistoryRepository.deleteHistorysByBusinessEntityId(supplier.getId());
  }
}
